<template>
  <div class="comment-list-container">
    <div class="comment-header">
      <h3>用户评论 ({{ comments.length }})</h3>
      <el-button type="primary" size="small" @click="showAddCommentForm">添加评论</el-button>
    </div>

    <el-divider />

    <!-- 评论列表 -->
    <div v-if="comments.length > 0" class="comment-list">
      <div v-for="comment in comments" :key="comment.commentId" class="comment-item">
        <div class="comment-info">
          <div class="user-avatar">
            <el-avatar :size="40" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
          </div>
          <div class="comment-content">
            <div class="comment-header">
              <span class="username">{{ comment.username || '匿名用户' }}</span>
              <span class="rating">
                <el-rate v-model="comment.rating" disabled text-color="#ff9900" />
              </span>
            </div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
          </div>
        </div>
        <!-- 管理员或本人可以删除评论 -->
        <div v-if="isAdmin || comment.userId === currentUserId" class="comment-actions">
          <el-button type="text" size="small" @click="handleEdit(comment)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(comment.commentId)">删除</el-button>
        </div>
      </div>
    </div>
    
    <!-- 无评论时显示 -->
    <el-empty v-else description="暂无评论" />

    <!-- 添加评论对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑评论' : '添加评论'" width="500px">
      <el-form :model="commentForm" :rules="rules" ref="commentFormRef" label-width="100px">
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="commentForm.rating" :max="5" />
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <el-input v-model="commentForm.content" type="textarea" rows="4" placeholder="请输入您的评论" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitComment">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCommentsByCarId, addComment, updateComment, deleteComment } from '@/api/comment'

const props = defineProps({
  carId: {
    type: [Number, String],
    required: true
  },
  // 当前用户ID，用于判断是否可以编辑/删除评论
  currentUserId: {
    type: [Number, String],
    default: null
  },
  // 是否是管理员
  isAdmin: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['refresh'])

// 评论列表
const comments = ref([])
// 对话框可见状态
const dialogVisible = ref(false)
// 是否是编辑模式
const isEdit = ref(false)
// 评论表单
const commentForm = reactive({
  commentId: null,
  carId: null,
  userId: null,
  content: '',
  rating: 5
})
// 表单验证规则
const rules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 3, max: 500, message: '评论内容长度在 3 到 500 个字符', trigger: 'blur' }
  ],
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ]
}

// 表单引用
const commentFormRef = ref(null)

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 加载评论
const loadComments = async () => {
  try {
    const response = await getCommentsByCarId(props.carId)
    comments.value = response || []
  } catch (error) {
    console.error('加载评论失败:', error)
    ElMessage.error('加载评论失败')
  }
}

// 显示添加评论表单
const showAddCommentForm = () => {
  if (!props.currentUserId) {
    ElMessage.warning('请先登录后再添加评论')
    return
  }

  isEdit.value = false
  commentForm.commentId = null
  commentForm.carId = props.carId
  commentForm.userId = props.currentUserId
  commentForm.content = ''
  commentForm.rating = 5
  dialogVisible.value = true
}

// 编辑评论
const handleEdit = (comment) => {
  isEdit.value = true
  commentForm.commentId = comment.commentId
  commentForm.carId = comment.carId
  commentForm.userId = comment.userId
  commentForm.content = comment.content
  commentForm.rating = comment.rating
  dialogVisible.value = true
}

// 删除评论
const handleDelete = (commentId) => {
  ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteComment(commentId)
      ElMessage.success('删除成功')
      loadComments()
      emit('refresh')
    } catch (error) {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    }
  }).catch(() => {})
}

// 提交评论
const submitComment = async () => {
  if (!commentFormRef.value) return
  
  try {
    await commentFormRef.value.validate()
    
    if (isEdit.value) {
      // 编辑评论
      await updateComment(commentForm)
      ElMessage.success('评论更新成功')
    } else {
      // 添加评论
      await addComment(commentForm)
      ElMessage.success('评论发布成功')
    }
    
    dialogVisible.value = false
    loadComments()
    emit('refresh')
  } catch (error) {
    console.error('提交评论失败:', error)
    ElMessage.error('提交评论失败')
  }
}

// 组件加载时获取评论
onMounted(() => {
  loadComments()
})

// 暴露方法给父组件
defineExpose({
  loadComments
})
</script>

<style scoped>
.comment-list-container {
  margin: 20px 0;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-info {
  display: flex;
  flex: 1;
}

.user-avatar {
  margin-right: 15px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.username {
  font-weight: bold;
  color: #333;
}

.comment-text {
  margin: 8px 0;
  color: #333;
  line-height: 1.5;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-actions {
  display: flex;
  align-items: flex-start;
}
</style> 